/*
*  CEGLESRenderNode.h
*  
*
*  Created by Alexander Trutchenko on 11/02/12.
*  Copyright 2012 LID. All rights reserved.
*
*/

#include "CEGLESRenderNode.h"

#include "externals/GLES-Render.h"
#include "Box2D.h"


using namespace cocos2d;

namespace cocosext {

////////////////////////////////////////////////////////
//
/** CEGLESRenderNode
 * 
*/
////////////////////////////////////////////////////////

CCNode* CEGLESRenderNode::node(b2World* world, float ptmRation)
{
	CEGLESRenderNode *pRet = new CEGLESRenderNode(world);
	CCAssert(pRet != NULL, NULL);
	if (pRet->init(ptmRation))
	{
		pRet->autorelease();
        return pRet;
	}
	else
	{
		CC_SAFE_DELETE(pRet)
		return NULL;
	}
}


CEGLESRenderNode::~CEGLESRenderNode()
{
	delete _debugDraw; _debugDraw = NULL;
}

bool CEGLESRenderNode::init(float ptmRation)
{
    //self init
//    if (!CCNode::init() )
//        return false;

	_debugDraw = new GLESDebugDraw(ptmRation * CCDirector::sharedDirector()->getContentScaleFactor());
	
	uint32 flags = 0;
	flags |= b2Draw::e_shapeBit;
	flags |= b2Draw::e_jointBit;
	flags |= b2Draw::e_aabbBit;
	flags |= b2Draw::e_pairBit;
	flags |= b2Draw::e_centerOfMassBit;
	_debugDraw->SetFlags(flags);

	_world->SetDebugDraw(_debugDraw);

    return true;
}

void CEGLESRenderNode::draw()
{
	CCNode::draw();

	// Default GL states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY
	// Needed states:  GL_VERTEX_ARRAY, 
	// Unneeded states: GL_TEXTURE_2D, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY
	glDisable(GL_TEXTURE_2D);
	glDisableClientState(GL_COLOR_ARRAY);
	glDisableClientState(GL_TEXTURE_COORD_ARRAY);
	
	_world->DrawDebugData();
	
	// restore default GL states
	glEnable(GL_TEXTURE_2D);
	glEnableClientState(GL_COLOR_ARRAY);
	glEnableClientState(GL_TEXTURE_COORD_ARRAY);
}


} // namespace cocosext
